/*
 * Copyright 2007-2008 by Matthias Buch-Kromann <mbk.isv@cbs.dk>.
 * 
 * This file is part of the Open-source Dependency Toolkit (OSDT),
 * see http://code.google.com/p/open-source-dependency-toolkit. 
 * 
 * The OSDT is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * The OSDT is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with the OSDT in the files COPYING and COPYING.LESSER. If
 * not, see http://www.gnu.org/licenses.
 */

package org.osdtsystem.functions;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.osdtsystem.graphs.GraphAccessor;
import org.osdtsystem.values.EdgeID;
import org.osdtsystem.values.Layer;
import org.osdtsystem.values.Node;
import org.osdtsystem.values.PointedEdge;
import org.osdtsystem.values.PointedEdgeID;

/**
 * A function that returns the union of all in-edges for nodes in
 * the input node list. 
 * @author Matthias Buch-Kromann <mbk.isv@cbs.dk>
 */
public class FuncInEdges extends AbstractFunction<PointedEdge> {
    SingletonFunction<Layer> layerFunction;
    List<Function<? extends Node>> innodes;
    
    public FuncInEdges(SingletonFunction<Layer> layer, Function<? extends Node>... innodes) {
        super(innodes);
        this.innodes = Arrays.asList(innodes);
        this.layerFunction = layer;
    }

    @Override
    public List<PointedEdge> _functionValue(LocalFunction<?, ?> caller, FunctionContext context,
            GraphAccessor accessor) {
        List<PointedEdge> list = new ArrayList<PointedEdge>();
        Layer layer = layerFunction.singletonFunctionValue(caller, context, accessor);
        for (Function<? extends Node> innodeFunction : innodes) {
            List<? extends Node> nodes = 
                    innodeFunction.functionValue(caller, context, accessor);
            for (Node node : nodes) {
                for (EdgeID edge : accessor.inEdges(caller, node.asNode(), layer))
                    list.add(new PointedEdgeID(
                            accessor.outNode(caller, edge), edge));
            }
        }
        return list;
    }

    @Override
    void toStringBuilder(FunctionStringBuilder builder) {
        builder.addSubfunction("layer", layerFunction);
        builder.addSubfunctions(innodes);
    }
}
